//
//  Factory.m
//  WBBaseProject
//
//  Created by 吴斌 on 2017/8/3.
//  Copyright © 2017年 吴斌. All rights reserved.
//
/**                            *********
 *                          如有疑问欢迎交流学习
 *                  新浪微博：http://weibo.com/535478908
 *         ********************************************************
 */

#import "Factory.h"

//#import "ValuePickerView.h"
//#import "FYLCityPickView.h"
//#import "FYLCityModel.h"

#import "LoginViewController.h"

@implementation Factory

/**
 判断是否登录
 
 @return 是否
 */
+ (BOOL)isLogin{
    NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:Token];
    if (!WB_IsNilString(login)) {
        return YES;
    }else{
        return NO;
    }
}

/**
 载入登陆界面
 */
+ (void)loadLoginScreen{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    UIWindow *window=[[[UIApplication sharedApplication] delegate] window];
    UINavigationController *loginNavi = [[UINavigationController alloc] initWithRootViewController:loginVC];
    [window.rootViewController presentViewController:loginNavi animated:YES completion:^{
    }];
}

/**
 自定义图文竖排按钮
 
 @param title 标题
 @param defImage 默认图片
 @param heightImage 高亮图片
 @return 按钮
 */
+ (UIButton *)customButtonWithTitle:(NSString *)title defImage:(NSString *)defImage heightImage:(NSString *)heightImage{
    UIButton *btn = [[UIButton alloc] init];
    [btn setImage:[UIImage imageNamed:defImage] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:heightImage] forState:UIControlStateSelected];
    [btn setTitle:title forState:UIControlStateNormal];
    btn.titleLabel.font = WB_Font(13);
    [btn setTitleColor:WB_HEX_COLOR(0xd3d3d3) forState:UIControlStateNormal];
    [btn setTitleColor:WB_HEX_COLOR(0xc4261d) forState:UIControlStateSelected];
    return btn;
}

/**
 所有返回按钮
 
 @param vc 控制器
 @return 按钮
 */
+ (UIButton *)backButton:(UIViewController *)vc{
    UIButton *btn = [[UIButton alloc] init];
//    btn.backgroundColor = [UIColor redColor];
    btn.frame = CGRectMake(0, 0, 80, 64);
    [btn setImageEdgeInsets:UIEdgeInsetsMake(0, -50, 0, 0)];
    [btn setImage:[UIImage imageNamed:@"leftBack_white"] forState:UIControlStateNormal];
    [btn setTitle:@"             " forState:UIControlStateNormal];
    //把视图的边角变为圆形, cornerRadius圆角半径
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    //弹簧控件, 修复边距
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    spaceItem.width = -5;
    vc.navigationItem.leftBarButtonItems = @[spaceItem,backItem];
    return btn;
}

+ (UIButton *)customButtonWithTitle:(NSString *)title
{
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectZero];
    btn.titleLabel.font = WB_FontSize(17);
    //让按钮文字居中
    btn.contentEdgeInsets = UIEdgeInsetsMake(-10, 0, 0, 0);
    [btn setTitle:title forState:UIControlStateNormal];
    UIImage *image = [UIImage imageNamed:@"button"];
    [btn setBackgroundImage:image forState:UIControlStateNormal];
    btn.adjustsImageWhenHighlighted = NO;
    return btn;
}

// 颜色转化图片
+ (UIImage*)createImageWithColor:(UIColor *)color{  
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);  
    UIGraphicsBeginImageContext(rect.size);  
    CGContextRef context = UIGraphicsGetCurrentContext();  
    CGContextSetFillColorWithColor(context, [color CGColor]);  
    CGContextFillRect(context, rect);  
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();  
    UIGraphicsEndImageContext();  
    return theImage;  
} 

/**
 json字符串转字典
 
 @param jsonString json字符串
 @return 字典数据
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if (error) {
        DebugLog(@"json解析失败：%@",error);
        return nil;
    }
    return dic;
}

/**
 倒计时功能
 
 @param btn 获取验证码按钮
 */
+ (dispatch_source_t)startTimeWithBtn:(UIButton *)btn{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0); // 每秒执行一次
    
    NSTimeInterval seconds = 120.f;
    NSDate *endTime = [NSDate dateWithTimeIntervalSinceNow:seconds]; // 最后期限
    
    dispatch_source_set_event_handler(_timer, ^{
        int interval = [endTime timeIntervalSinceNow];
        if (interval > 0) { // 更新倒计时
            NSString *timeStr = [NSString stringWithFormat:@"%ds后重发", interval];
            DebugLog(@"%@",timeStr);
            dispatch_async(dispatch_get_main_queue(), ^{
                btn.enabled = NO;
//                [btn setBackgroundColor:WB_HEX_COLOR(0xf5f5f5)];
//                [btn setTitleColor:WB_HEX_COLOR(0xa8a8a8) forState:UIControlStateNormal];
                //设置界面的按钮显示
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [btn setTitle:timeStr forState:UIControlStateNormal];
                [UIView commitAnimations];
            });
        } else { // 倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                btn.enabled = YES;
                //设置界面的按钮显示  根据自己需求设置
//                WB_ViewBorderRadius(btn, 3, 1, [UIColor whiteColor]);
                [btn setTitle:@"重新发送" forState:UIControlStateNormal];
//                [btn setTitleColor:WB_HEX_COLOR(0x5f9bfa) forState:UIControlStateNormal];
//                [btn setBackgroundColor:[UIColor whiteColor]];
            });
        }
    });
    dispatch_resume(_timer);
    return _timer;
}


/**
 验证手机号码
 
 @param number 手机号码
 @return 是否是手机号码
 */
+ (BOOL)isPhoneNumber:(NSString *)number{
    //#if versionFlag == 0
    //    NSString *phoneRegex1=@"1[34578]([0-9]){9}";
    //#else
    //    NSString *phoneRegex1=@"1[34578]([0-9]){9}";
    NSString *phoneRegex1 = @"^(13[0-9]|11[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])[0-9]{8}$";
    
    //#endif
    
    NSPredicate *phoneTest1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex1];
    return  [phoneTest1 evaluateWithObject:number];
}

//密码控制数字和字母
+ (BOOL)passwordCheck:(NSString *)password
{
    NSString *carRegex = @"^[a-zA-Z0-9]{6,20}$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    return [carTest evaluateWithObject:password];
}

/**
 字典转json
 
 @param dic 字典
 @return json字符串
 */
+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

//获取用户信息
+ (void)getUesrInfo 
{
    [XYHttpRequest dataRequestWithGetUserInfoSuccess:^(id responseObj) {
        if (Success) {
            [[NSUserDefaults standardUserDefaults] setObject:responseObj[@"data"][@"user"] forKey:UserInfo];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    } failure:^(NSError *error) {
    }];
}

@end
